import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screen_record/flutter_screen_record.dart';

///后台取证权限设置-主要是 Android的应用保活 白名单
class SettingBackgroundWidget extends StatefulWidget {
  final double titleFontSize;
  final double contentFontSize;
  final String appName;
  ///手机型号
  final String brand;
  ///允许的值为 notary、pro、cloud
  final String appCode;
  final Color? buttonColor;
  final EdgeInsetsGeometry textPadding;
  final Function(String text)? onToast;
  final Function(String text)? onGuide;

  SettingBackgroundWidget({
    Key? key,
    this.titleFontSize = 15,
    this.contentFontSize = 13,
    this.buttonColor,
    this.onToast,
    this.onGuide,
    this.textPadding = const EdgeInsets.symmetric(vertical: 12, horizontal: 15),
    required this.appName,
    required this.brand,
    required this.appCode,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => SettingBackgroundWidgetState();

}

class SettingBackgroundWidgetState extends State<SettingBackgroundWidget>{

  List<Map<String,dynamic>> getDescBackground(String appName) => [
    {
      "title": "请勿开启\"省电模式\"",
      "desc": "如果开启了省电模式，将导致后台取证进程关闭，导致取证失败。建议后台录屏录像过程中，关闭省电模式。"
    },
    {
      "title": "电池优化白名单设置",
      "desc": "由于系统的省电设置，可能在后台录屏、录像过程中，误杀进程导致取证失败，请您将应用名称“$appName”加入电池保护名单中。",
      "btn": "快速设置"
    },
    {
      "title": "后台运行权限设置",
      "desc": "为避免后台录屏、录像取证失败，建议您为“$appName”，开启自启动运行权限。在设置中，搜索后台，进入应用自启动管理/自动管理，开启允许后台活动。",
      "btn": "快速设置",
      "guide":true,
      "type":"background"
    },
    {
      "title": "后台任务加锁",
      "desc": "打开后台任务加锁，可以避免$appName被清理程序清理，避免该原因导致的录屏退出问题。",
      "guide":true,
      "type":"lock"
    },
    {
      "title": "微信录屏",
      "desc": "使用小米或红米录制微信信息，打开微信之后请参照截图的方式打开屏幕共享，否则录制出来的证据不可用。",
    },
  ];

  late final List data = getDescBackground(widget.appName);
  final Map<String,ValueNotifier<String?>> notify = {};

  String get _brand {
    String b = widget.brand.toLowerCase();
    if(b.contains("xiaomi")) {
      return "xiaomi";
    } else if(b.contains("redmi")) {
      return "xiaomi";
    }
    return b;
  }

  @override
  Widget build(BuildContext context) {
    var list = <Widget>[];
    list.add(Padding(padding: widget.textPadding, child: Text('截图最多只能截取1000张')));
    
    for (var item in data) {
      var btn = item["btn"];
      var title = item["title"];
      if (btn == null) {
        //小米手机的录屏需要开启屏幕共享功能
        if("微信录屏".compareTo(title) == 0) {
          if("xiaomi".compareTo(_brand) == 0) {
            list.add(getTitle(title));
            list.add(getText(item["desc"], item['type'], item['guide']));
            list.add(Image.asset('assets/mi_secure.jpg', package: 'flutter_screen_record', scale: 2));
          }
        } else {
          list.add(getTitle(title));
          list.add(getText(item["desc"], item['type'], item['guide']));
        }
      } else {
        ValueNotifier<String?> v = notify[title] ??= ValueNotifier<String?>(null);
        func() {
          if (title == "电池优化白名单设置") {
            ignoreBattery(v);
          } else if (title == "后台运行权限设置") {
            setBackground(v);
          }
        }

        var r = Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [getTitle(title), getButton(btn, func)],
        );
        list.add(r);
        list.add(getText(item["desc"], item['type'], item['guide']));
        list.add(getTips(v));
      }
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: list,
    );
  }

  Widget getTips(ValueNotifier<String?> v) {
    var pad = widget.textPadding.subtract(EdgeInsets.symmetric(vertical: 4));
    return ValueListenableBuilder<String?>(
        valueListenable: v,
        builder: (context, v, c) {
          return Visibility(
              visible: v != null && v.isNotEmpty,
              child: getText(
                v ?? "",
                "",
                false,
                color: Colors.redAccent,
                padding: pad,
              ));
        });
  }

  Widget getTitle(String data) {
    return getText(data, "", false,
        fontSize: widget.titleFontSize,
        color: const Color(0xFF111111),
        fontWeight: FontWeight.w500);
  }

  Widget getText(String data, String? type, bool? guide, {
    double? fontSize,
    Color color = const Color(0xFF333333),
    FontWeight? fontWeight,
    EdgeInsetsGeometry? padding,
  }) {
    return Padding(
      padding: padding ?? widget.textPadding,
      child: RichText(
        softWrap: true,
        text: TextSpan(
            text: data,
            children: guide == true ? [
              TextSpan(text: '查看教程>',
                  style: TextStyle(color: widget.buttonColor ?? Colors.redAccent, decoration: TextDecoration.underline),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      String url = "https://app-static.fxnotary.com/html/guide.html?from=${widget.appCode}&type=$type&brand=${_brand}";
                      if(widget.onGuide != null) widget.onGuide!(url);
                      else {
                        print('You must set onGuide Function to Open url.');
                      }
                    })
            ] : [],
            style: TextStyle(
              fontSize: fontSize ?? widget.contentFontSize,
              color: color,
              fontWeight: fontWeight,
            )),
      ),
    );
  }

  Widget getButton(String data, Function() onTap) {
    var style =
        TextStyle(fontSize: widget.contentFontSize, color: Colors.white);
    return Container(
        height: 35,
        margin: const EdgeInsets.only(right: 15),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(20),
          child: Material(
              color: widget.buttonColor ?? Colors.redAccent,
              child: InkWell(
                onTap: onTap,
                child: Center(
                    child: Padding(
                  padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
                  child: Text(data, style: style),
                )),
              )),
        ));
  }

  _toToast(ValueNotifier<String?> tips, String toast) {
    widget.onToast?.call(toast);
    tips.value = toast;
    Future.delayed(Duration(seconds: 5), (){
      tips.value = null;
    });
  }

  ///忽略 电量优化
  ignoreBattery(ValueNotifier<String?> tips) async {
    var can = await FlutterScreenRecord.isIgnoreBatteryOptimizations();
    var res = await FlutterScreenRecord.requestIgnoreBatteryOptimizations();
    if (res != true && can == true) {
      _toToast(tips, "当前手机无电量优化功能，可以不用设置");
    }
    if (res != true) {
      _toToast(tips, "当前电池优化白名单开启失败，可以到设置中开启");
    }
  }

  ///自动启动管理
  setBackground(ValueNotifier<String?> tips) async {
    var res = await FlutterScreenRecord.toBootManagerActivity();
    if (res == null) {
      _toToast(tips, "开启失败，可以到设置中开启");
    }
    if (res != true) {
      _toToast(tips, "当前后台运行权限页面开启失败，可以到设置中开启");
    }
  }
}
